/**   
* @Description: 是否是数字校验处理类 
*/ 
package org.kskj.ipw.validator.handle;

import java.lang.annotation.Annotation;
import java.util.regex.Pattern;

import org.kskj.ipw.exception.ValidateException;
import org.kskj.ipw.validator.ValidatorConstant;
import org.kskj.ipw.validator.annotation.IsDigit;
import org.springframework.util.StringUtils;

/** 
* @author sztan 
* @date 2016年8月9日 下午4:01:44 
* @version 1.0 
*/
public class IsDigitValidatorHandle implements ValidatorHandle {

	@Override
	public void validate(final Annotation annotation, final Object parameterValue) throws ValidateException {
		String handle = ((IsDigit)annotation).handle();
		String message = ((IsDigit)annotation).message();
		// 不为空且不等于默认的处理汉德勒handle
		if(!StringUtils.isEmpty(handle) && !ValidatorConstant.IS_DIGIT_HANDLE.equals(handle)) { //优化点:  这里用的是spring的字符春处理类，如果日后要封装成组件还需自己写
			// 自定义
			try {
			  Class<?> clazz = Class.forName(handle);
			  ((ValidatorHandle)clazz.newInstance()).validate(annotation, parameterValue);
			} catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
				throw new RuntimeException(e);
			}
		} else {
			String value = (String)parameterValue;
			String patternStr = "\\d*";
			Pattern pattern = Pattern.compile(patternStr);
			if (value != null && !"".equals(value)) {
				if (!pattern.matcher(value).matches()) {
					throw new ValidateException(message + " The value is:" + value);
				}
			}
		}
	}

}
